package com.lsc.jdbc.demo.jdbc.util;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

/**
 * 数据库链接工具类  DBCP
 */
public class JdbcUtils_DBCP {

    static Connection connection;
    static DataSource dataSource;

    static {
        /* 1. 使用 Properties 配置类对象 来 读取 数据 */
        Properties properties = new Properties();
        try {
            properties.load(JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcp.txt"));
            /* 使用工厂模式 开箱即用 */
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Connection getCon() {

        try {
            connection = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet, PreparedStatement preparedStatement) {

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

    }


}
